package com.shop.auth.controller;


import com.shop.auth.dto.request.LoginRequest;
import com.shop.auth.dto.request.SignupRequest;
import com.shop.auth.dto.response.JwtResponse;
import com.shop.auth.repository.UserRepository;
import com.shop.auth.service.AuthService;
import com.shop.common.enums.ExceptionEnum;
import com.shop.common.exception.OperationException;
import com.shop.common.response.ExceptionResponse;
import com.shop.auth.model.User;
import com.shop.servlet.utils.UserSecurity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("auth")
public class AuthController {
    @Autowired
    UserRepository userRepository;
    @Autowired
    PasswordEncoder encoder;

      @Autowired
    private AuthService authService;

    // 处理注册请求, BindingResult bindingResult
    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody @Validated SignupRequest signUpRequest) {
        if(userRepository.existsByUsername(signUpRequest.getUsername())){
            throw new OperationException(ExceptionEnum.USERNAME_ALREADY_EXISTS);
        }
        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(signUpRequest.getEmail())) {
            throw new OperationException(ExceptionEnum.EMAIL_ALREADY_EXISTS);
        }
        // 创建新用户账号
        User user = new User();
        user.setName(signUpRequest.getName());
        user.setUsername(signUpRequest.getUsername());
        user.setEmail(signUpRequest.getEmail());
        user.setPassword(encoder.encode(signUpRequest.getPassword()));  // 加密密码
        user.setPhone(signUpRequest.getPhone());
        user.setAddress(signUpRequest.getAddress());
        userRepository.save(user);  // 保存用户到数据库
        return ResponseEntity.ok(ExceptionResponse.Success());
    }
    @PostMapping("login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        JwtResponse jwtResponse = authService.login(loginRequest.getUsername(), loginRequest.getPassword());
        return ResponseEntity.ok(ExceptionResponse.Success(jwtResponse));
    }
    @GetMapping("username")
    public User username(@RequestParam String username)  {
        return userRepository.findByUsername(username);
    }
    @GetMapping("userInfo")
    public User userInfo(@RequestParam Long user_id)  {
        return userRepository.findById(user_id).orElse(null);
    }
    @GetMapping("test")
    public String test()  {
       //  throw new OperationException(ExceptionEnum.CONFLICT);


        //return ResponseEntity.ok(ExceptionResponse.Success());
        return "auth_test";
    }
}
